package net.shambolica.ember.utils;

import com.ericsson.otp.erlang.OtpEpmd;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Utilities for node/mbox creation and naming.
 */
public class NodeUtils {

    protected static final Logger log = LoggerFactory.getLogger(NodeUtils.class);


    public static volatile String globalHostNodeNamePrefix = "ember_host";
    public static volatile String globalGuestNodeNamePrefix = "ember_guest";


    public static String createNodeName() {
        return createHostNodeName(null);
    }

    public static String createHostNodeName(String postfix) {
        return RuntimeUtils.createNodeName(globalHostNodeNamePrefix, postfix);
    }

    public static String createGuestNodeName(String postfix) {
        return RuntimeUtils.createNodeName(globalGuestNodeNamePrefix, postfix);
    }

    public static boolean isEpmdRunning() {
        try {
            Collection<String> others = getRegisteredNamesOnEpmd();
            return true;
        } catch (IOException e) {
            return false;
        }
    }

    public static Collection<String> getRegisteredNamesOnEpmd() throws IOException {
        final String[] lookupResult = OtpEpmd.lookupNames();
        Collection<String> ret = new ArrayList<String>(lookupResult.length);
        for (String line: lookupResult) {
            String[] parts = line.split("\\s+");
            try {
                ret.add(parts[1]);
            } catch (ArrayIndexOutOfBoundsException e) {
                log.debug("silencing epmd reg list unexpected out of bounds, line='{}'", line, e);
            }
        }
        return ret;
    }


    public static String getFullNodeName(String shortName) {
        InetAddress localhost = null;
        try {
            localhost = InetAddress.getLocalHost();
            String localHostName = localhost.getHostName();
            return shortName+"@"+localHostName;
        } catch (UnknownHostException e) {
            log.error("unable to get local host name: {}: {}",
                    e.getClass().getName(), e.getMessage());
            return null;
        }
    }
}
